/*
 *  Copyright 2009 David Kuhn <david.s.kuhn at gmail.com>.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package com.google.code.teamtools.client.controller;

import com.extjs.gxt.ui.client.event.MvcEvent;
import com.google.code.teamtools.client.view.*;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.DispatcherListener;
import com.google.code.teamtools.client.AppEvents;

/**
 * 
 * @author David Kuhn <david.s.kuhn at gmail.com>
 */
public class AppController extends Controller
{
    private AppView appView;

    public AppController()
    {
        registerEventTypes(AppEvents.Init);
        registerEventTypes(AppEvents.Login);
        registerEventTypes(AppEvents.Error);

        /* Listen for dispatcher events. This is used to trigger subsequent
         * events such as performing the initial navigation once the UI is
         * initialised. */
        Dispatcher.get().addDispatcherListener(
            new DispatcherListener()
            {
                @Override
                public void afterDispatch(MvcEvent mvce)
                {
                    // Once UI initialised navigate to team view.
                    if (mvce.getAppEvent().getType() == AppEvents.Init)
                        Dispatcher.forwardEvent(AppEvents.NavTeam);
                }
            }
        );
    }

    public void handleEvent(AppEvent event)
    {
        EventType type = event.getType();
        if (type == AppEvents.Init) {
            onInit(event);
        } else if (type == AppEvents.Login) {
            onLogin(event);
        } else if (type == AppEvents.Error) {
            onError(event);
        }
    }

    @Override
    public void initialize()
    {
        appView = new AppView(this);
    }

    protected void onError(AppEvent ae)
    {
        System.out.println("error: " + ae.<Object>getData());
    }

    private void onInit(AppEvent event)
    {
        forwardToView(appView, event);
    }

    private void onLogin(AppEvent event)
    {
        forwardToView(appView, event);
    }
}
